package com.itmg.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.itmg.dao.BrandDAO;
import com.itmg.dao.model.BrandModel;

public class BrandDAOImpl extends SqlMapClientDaoSupport implements BrandDAO{

	public List<BrandModel> getBrand()  throws Exception {
		List<BrandModel> list = new ArrayList<BrandModel>();
		Connection con = null;
		String sql = "select * from shop_brand";
		try {
			con = getSqlMapClientTemplate().getDataSource().getConnection();
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery(sql);
			while(rs.next()){
				BrandModel model = new BrandModel();
				model.setName(rs.getString("name"));
				model.setCategory(rs.getString("category"));
				model.setAlias(rs.getString("alias"));
				list.add(model);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
	
    public void saveBrandCache(BrandModel model) throws Exception{
		Connection con = null;
		String sql = "insert into shop_brand_cache (productMd5,name) values (?,?)";
		try {
			con = getSqlMapClientTemplate().getDataSource().getConnection();
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setString(1, model.getProductMd5());
			ps.setString(2,model.getName());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
    }
	
	public BrandModel getBrandCahce(String productMd5) throws Exception{
		Connection con = null;
		String sql = "select * from shop_brand_cache where productMd5 = ?";
		BrandModel model = new BrandModel();
		try {
			con = getSqlMapClientTemplate().getDataSource().getConnection();
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setString(1, productMd5);
			ResultSet rs = ps.executeQuery();
			rs.next();
			model.setName(rs.getString("name"));
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return model;
	}

	
}
